package cn.maihe.elg.operation.service.system;

import cn.maihe.elg.operation.model.vo.system.SendSmsRespDTO;
import cn.maihe.elg.operation.repository.entity.SmsDO;
import cn.maihe.elg.operation.repository.entity.SmsDOCondition;
import cn.maihe.elg.operation.service.BaseDaoService;
import cn.maihe.elg.operation.supports.sms.AliyunSmsService;
import cn.maihe.elg.operation.supports.sms.HuaWeiCloudSmsService;
import cn.maihe.elg.operation.supports.sms.TencentCloudSmsService;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.framework.starter.mybatis.dao.MybatisDaoImpl;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Description
 * @Author caixh
 * @Date 2021/8/11.
 */
@Service
@Slf4j
public class SmsService  extends BaseDaoService<SmsDO> {

    @Resource
    private AliyunSmsService aliyunSmsService;
    @Resource
    private TencentCloudSmsService tencentCloudSmsService;
    @Resource
    private HuaWeiCloudSmsService huaWeiCloudSmsService;

    private String minute = "15";
    private int minute_i = 15*60*1000;

    public int getMobileCount(String mobile) {
        String today = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
        return MybatisDaoImpl.run().selectCount(
                SmsDOCondition.builder().andMobileEq(mobile).andCreateTimeGe(DateUtil.getDateFromString(today)).build());
    }

    public SendSmsRespDTO sendSms(SmsDO smsDO) {
        SendSmsRespDTO respDTO = new SendSmsRespDTO();

        try {
//            tencentCloudSmsService.sendAuthCodeSms(smsDO.getMobile(),smsDO.getCode(),minute);
            String[] parasArray = {smsDO.getCode()};
            String templateParas = JSON.toJSONString(parasArray);
            huaWeiCloudSmsService.sendSms(smsDO.getMobile(), null, templateParas);
            log.info("验证码发送，手机号：{}，验证码：{}",smsDO.getMobile(),smsDO.getCode());
        } catch (RuntimeException e) {
            log.error("短信发送失败",e);
            respDTO.setStatus("FAIL");
            respDTO.setMsg("验证码发送失败，请稍后再试");
            return respDTO;
        }
        this.insert(smsDO);

        respDTO.setStatus("SUC");
        respDTO.setMsg("验证码已发送，请注意查收");
        return respDTO;
    }

    public SendSmsRespDTO checkSmsCode(String mobile, String code) {
        SendSmsRespDTO respDTO = new SendSmsRespDTO();

        Date date = new Date();
        date.setTime(date.getTime()-minute_i);
        int count = MybatisDaoImpl.run().selectCount(
                SmsDOCondition.builder().andMobileEq(mobile).andCodeEq(code).andCreateTimeGe(date).build());

        if(count>0){
            respDTO.setStatus("SUC");
            respDTO.setMsg("验证码校验通过");
            return respDTO;
        }

        respDTO.setStatus("FAIL");
        respDTO.setMsg("验证码校验失败");
        return respDTO;

    }
}
